package org.jeecg.modules.wo.people.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.wo.nucleicmessage.entity.WoNucleicMessage;
import org.jeecg.modules.wo.nucleicmessage.service.IWoNucleicMessageService;
import org.jeecg.modules.wo.people.entity.WoPeople;
import org.jeecg.modules.wo.people.mapper.WoPeopleMapper;
import org.jeecg.modules.wo.people.service.IWoPeopleService;
import org.jeecg.modules.wo.persontype.service.IWoPersonTypeService;
import org.jeecg.modules.wo.utils.KyqApiUtils;
import org.jeecg.modules.wo.wobasepeople.entity.WoBasePeople;
import org.jeecg.modules.wo.wobasepeople.service.IWoBasePeopleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description: 人员管理
 * @Author: jeecg-boot
 * @Date:   2022-03-22
 * @Version: V1.0
 */
@Service
@Slf4j
public class WoPeopleServiceImpl extends ServiceImpl<WoPeopleMapper, WoPeople> implements IWoPeopleService {
    @Autowired
    IWoNucleicMessageService iWoNucleicMessageService;
    @Autowired
    private IWoPersonTypeService woPersonTypeService;
    @Autowired
    private IWoBasePeopleService woBasePeopleService;
       /**
     * 将列表人员更新至基础人员表，主要为了解决 同一个人被不同单位管理时，用基础人员表去请求核酸检测数据
     * 以避免同一个人 被请求多次；
     * 但 目前系统仅应用于学校，基本不存在人员重复的情况，暂时弃用
     * @param woPeople
     * @return
     */
    private String saveOrUpdateBasePeople(WoPeople woPeople){
        WoBasePeople sp=null;
        QueryWrapper<WoBasePeople> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("per_idcard",woPeople.getPerIdcard());
        sp=woBasePeopleService.getOne(queryWrapper);
        if(sp==null){
            sp=new WoBasePeople();
            sp.setPerIdcard(woPeople.getPerIdcard());
        }
        sp.setPerName(woPeople.getPerName());
        sp.setPerDatebirth(woPeople.getPerDatebirth());
        sp.setPerPhoto(woPeople.getPerPhoto());
        sp.setPerNucleiccode(woPeople.getPerNucleiccode());
        sp.setPerTel(woPeople.getPerTel());
        sp.setPerSex(woPeople.getPerSex());
        woBasePeopleService.saveOrUpdate(sp);
        return sp.getId();
    }

    /**
     * 通过核酸检测接口获取核酸检测数据
     * @param peopleList 人员列表
     */
    private void getInsp(List<WoPeople> peopleList) {
        for(WoPeople basePsn:peopleList){
            if(StringUtils.isBlank(basePsn.getPerNucleiccode())){
                //人员没有抗疫情编码则不执行获取核酸检测记录
                continue;
            }
            ////通过接口获取核酸检测数据
            JSONObject inspObj= KyqApiUtils.getInspByKyqCode(basePsn.getPerNucleiccode());
            if(inspObj!=null&&inspObj.getInteger("status")==200){
                JSONObject dataObj=inspObj.getJSONObject("data");
                basePsn.setNucleicAddress(dataObj.getString("detectionName"));//核酸检测点
                basePsn.setNucleicDate(dataObj.getDate("feedBackTime"));//核酸检测时间
                basePsn.setNucleicResult(dataObj.getString("checkResult"));//核酸检测结果
                this.updateById(basePsn);
                //log.info(String.format("定时任务，获取人员 姓名："+basePsn.getPerName()+",核酸检测数据成功！时间:" + DateUtils.getTimestamp()));
            }else{
                log.warn(String.format("定时任务，获取人员 姓名："+basePsn.getPerName()+",核酸检测数据失败！时间:" + DateUtils.getTimestamp()));
            }
        }
    }

    /**
     * 通过门禁接口获取核酸检测数据
     *  @param peopleList 人员列表
     */
    private void getInspByDevice(List<WoPeople> peopleList) {
        for(WoPeople psn:peopleList) {
            JSONObject inspObj=null;
            if (StringUtils.isNotBlank(psn.getPerNucleiccode())) {
                //人员没有抗疫情编码
                /**
                 * 通过抗疫情编码 从抗疫情获取核酸检测记录
                 */
                inspObj= KyqApiUtils.nucleicAcidTest(4,psn.getPerNucleiccode(),2,"","");
            }else if(StringUtils.isNotBlank(psn.getPerIdcard())){
                /**
                 * 通过人员身份证号码 从抗疫情获取核酸检测记录
                 */
                inspObj= KyqApiUtils.nucleicAcidTest(3,psn.getPerIdcard(),2,"","");
            }else{continue;}
            if(inspObj.getInteger("code").equals(0)&&inspObj.getString("msg").equals("success")){
                JSONObject data= (JSONObject) inspObj.get("data");
                if(data!=null){
                    psn.setPerNucleiccode(data.getString("personId"));
                    //将最新核酸检测信息更新至人员表
                    psn.setNucleicAddress("");//核酸检测点，设备接口 无该项数据返回
                    psn.setNucleicDate(data.getDate("confirmTime"));
                    psn.setNucleicResult(data.getString("checkResult"));
                    this.updateById(psn);
                    log.info(String.format("定时任务，获取人员 姓名："+psn.getPerName()+",核酸检测数据成功！时间:" + DateUtils.getTimestamp()));
                }else{
                    log.warn(String.format("定时任务，获取人员 姓名："+psn.getPerName()+",核酸检测数据失败！时间:" + DateUtils.getTimestamp()));
                }
            }else{
                log.warn(String.format("定时任务，获取人员 姓名："+psn.getPerName()+",核酸检测数据失败！时间:" + DateUtils.getTimestamp()));
            }
        }
    }

    /**
     *
     * @param apiModel
     * @param typeId 分组id
     * @param day 核酸检测时间 距离现在的时间天数，超过这个天数的再进行核酸数据获取
     */
    @Override
    public void getNucleicByType(String apiModel, String typeId, Integer day) {
        QueryWrapper<WoPeople> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(typeId)){
            String ids=woPersonTypeService.queryTreeChildIds(typeId);
            queryWrapper.in("psn_type_id",ids.split(","));
        }
        if(day>0){
            Date now=new Date();
            int s = day*24*60*60;// 将day天转换为秒
            Date bTime=DateUtils.addTime(now, Calendar.SECOND,-s);
            queryWrapper.notBetween("nucleic_date", bTime,now).or().isNull("nucleic_date");
        }
        List<WoPeople>  peopleList=this.list(queryWrapper);
        if("device".equals(apiModel)){//设备接口模式
            getInspByDevice(peopleList);
        }else{//普通核酸检测数据查询接口模式
           getInsp(peopleList);
        }
    }
 }
